from 核心.配置文件 import settings
from 核心.解密数据 import vp
from 核心.公共函数 import comm
from 核心.数据操作 import MySQLCRUD
import requests, json, time


class ScanComic:
    ##初始化
    def __init__(self):
        self.web_url = settings.BASE_URL
        self.comm = comm
        # 初始化数据库连接
        self.db = None
        self.init_database()
        # 批量插入的缓冲区
        self.batch_buffer = []
        self.batch_size = 100  # 每100条数据批量插入一次
        # 章节批量插入的缓冲区
        self.chapter_buffer = []
        self.chapter_batch_size = 100  # 每100条章节数据批量插入一次
    ##初始化数据库连接
    def init_database(self):
        """初始化数据库连接，使用增强的MySQLCRUD类"""
        try:
            # 使用增强的MySQLCRUD类，支持自动重连
            db_config = {
                **settings.DB_CONFIG,
                'max_retries': 3,         # 最大重试次数
                'connection_timeout': 60  # 连接超时时间
            }
            
            self.db = MySQLCRUD(**db_config)
            
            if not self.db.is_connected():
                print("数据库连接失败！")
                return False
            else:
                print("数据库连接成功！")
                print(f"连接池状态: {self.db.get_pool_status()}")
                return True
                
        except Exception as e:
            print(f"数据库初始化失败: {e}")
            return False

    ##执行数据库查询（使用MySQLCRUD类）
    def execute_query_with_retry(self, query, params=None, max_retries=3):
        """执行数据库查询，使用MySQLCRUD类的重连机制"""
        return self.db.execute_query(query, params)
        
    ##执行数据库更新（使用MySQLCRUD类）
    def execute_update_with_retry(self, query, params=None, max_retries=3):
        """执行数据库更新，使用MySQLCRUD类的重连机制"""
        try:
            print(f"执行UPDATE语句: {query}")
            print(f"参数: {params}")
            print(f"参数类型: {[type(p) for p in params] if params else 'None'}")
            
            # 使用MySQLCRUD类的execute_update方法执行UPDATE（不是execute_query！）
            affected_rows = self.db.execute_update(query, params)
            print(f"UPDATE影响行数: {affected_rows}")
            
            # 检查是否真的更新了数据
            if affected_rows > 0:
                print(f"✓ UPDATE成功，影响了 {affected_rows} 行")
                return True
            else:
                print(f"⚠ UPDATE执行了，但没有影响任何行")
                return False
                
        except Exception as e:
            print(f"UPDATE执行异常: {e}")
            import traceback
            traceback.print_exc()
            return False
        
    ##检查并确保数据库连接
    def ensure_database_connection(self):
        """检查数据库连接状态，如果断开则尝试重连"""
        if not self.db or not self.db.is_connected():
            print("检测到数据库连接断开，尝试重新连接...")
            if self.init_database():
                print("数据库重连成功")
                return True
            else:
                print("数据库重连失败")
                return False
        return True
            
    ##通用JSON字段处理函数
    def _process_json_field(self, field_value, field_name):
        """通用JSON字段处理函数，自动检测类型并转换"""
        if isinstance(field_value, str):
            # 如果已经是字符串，直接使用
            return field_value
        elif isinstance(field_value, list):
            # 如果是列表，转换为JSON字符串
            json_string = json.dumps(field_value, ensure_ascii=False)
            return json_string
        else:
            # 其他类型转换为字符串
            string_value = str(field_value) if field_value else '[]'
            return string_value
            
    ##批量插入漫画详情到数据库
    def batch_insert_comic_detail(self, comic_data, domain=None):
        """批量插入漫画详情数据到数据库（在事务中调用，不自动提交）"""
        if not self.db or not self.db.is_connected():
            print("数据库未连接，无法插入数据")
            return False
            
        try:
            # 确保JSON字段正确序列化
            station_list = comic_data.get('stationList', [])
            class_list = comic_data.get('classList', [])
            tag_list = comic_data.get('tagList', [])
            
            # 使用通用函数处理所有可能的JSON字段
            station_list_json = self._process_json_field(station_list, 'station_list')
            class_list_json = self._process_json_field(class_list, 'class_list')
            tag_list_json = self._process_json_field(tag_list, 'tag_list')
            
            comic_record = {
                'comic_id': comic_data.get('id'),
                'comics_id': comic_data.get('comicsId'),
                'comics_title': comic_data.get('comicsTitle', ''),
                'cover_img': comic_data.get('coverImg', ''),
                'back_img': comic_data.get('backImg', ''),
                'station_list': station_list_json,
                'tag_list': tag_list_json,
                'class_list': class_list_json,
                'work_category': comic_data.get('workCategory', ''),
                'author_name': comic_data.get('authorName', ''),
                'info': comic_data.get('info', ''),
                'chapter_new_num': comic_data.get('chapterNewNum'),
                'type': comic_data.get('type'),
                'update_status': comic_data.get('updateStatus'),
                'fake_likes': comic_data.get('fakeLikes'),
                'fake_watch_times': comic_data.get('fakeWatchTimes'),
                'fake_favorites': comic_data.get('fakeFavorites'),
                'comment_num': comic_data.get('commentNum'),
                'user_id': comic_data.get('userId'),
                'nick_name': comic_data.get('nickName', ''),
                'logo': comic_data.get('logo', ''),
                'is_like': comic_data.get('isLike', ''),
                'is_favorite': comic_data.get('isFavorite', ''),
                'last_read_chapter_id': comic_data.get('lastReadChapterId'),
                'created_at': comic_data.get('createdAt', ''),
                'updated_at': comic_data.get('updatedAt', ''),
                'domain': domain or '',
                'scan_time': time.strftime('%Y-%m-%d %H:%M:%S')
            }
            
            self.batch_buffer.append(comic_record)
            
            # 当缓冲区达到指定大小时，执行批量插入
            if len(self.batch_buffer) >= self.batch_size:
                insert_success = self._execute_batch_insert_comic_detail()
                if not insert_success:
                    return False
                    
        except Exception as e:
            print(f"准备批量插入漫画详情数据时出错: {e}")
            return False
            
        return True
        
    ##执行漫画详情批量插入
    def _execute_batch_insert_comic_detail(self):
        """执行实际的漫画详情批量插入操作，使用UPSERT提高性能（在事务中调用，不自动提交）"""
        if not self.batch_buffer:
            return True
            
        try:
            # 构建UPSERT SQL语句
            columns = [
                'comic_id', 'comics_id', 'comics_title', 'cover_img', 'back_img', 
                'station_list', 'tag_list', 'class_list', 'work_category', 'author_name',
                'info', 'chapter_new_num', 'type', 'update_status', 'fake_likes', 
                'fake_watch_times', 'fake_favorites', 'comment_num', 'user_id', 'nick_name',
                'logo', 'is_like', 'is_favorite', 'last_read_chapter_id', 'created_at', 
                'updated_at', 'domain', 'scan_time'
            ]
            
            # 构建INSERT部分
            placeholders = ', '.join(['%s'] * len(columns))
            insert_part = f"INSERT INTO comics_detail ({', '.join(columns)}) VALUES ({placeholders})"
            
            # 构建ON DUPLICATE KEY UPDATE部分
            update_columns = [col for col in columns if col not in ['id', 'comic_id', 'comics_id', 'created_at']]
            update_part = ', '.join([f"{col} = VALUES({col})" for col in update_columns])
            
            # 完整的UPSERT SQL
            query = f"{insert_part} ON DUPLICATE KEY UPDATE {update_part}"
            
            # 准备批量数据
            batch_data = []
            for record in self.batch_buffer:
                values = [record[col] for col in columns]
                batch_data.append(values)
            
            # 使用新的重连机制执行批量插入（不自动提交）
            success = self._execute_batch_insert_with_retry(query, batch_data, "comics_detail")
            
            if success:
                # 清空缓冲区
                self.batch_buffer.clear()
                return True
            else:
                return False
            
        except Exception as e:
            print(f"批量插入漫画详情失败: {e}")
            print(f"SQL语句: {query}")
            return False
                
    ##执行批量插入（使用MySQLCRUD类）
    def _execute_batch_insert_with_retry(self, query, batch_data, table_name, max_retries=3):
        """执行批量插入，使用MySQLCRUD类的重连机制（在事务中调用，不自动提交）"""
        try:
            # 尝试执行批量UPSERT
            try:
                result = self.db.execute_batch(query, batch_data)
                if result is not None:
                    print(f"成功处理 {len(batch_data)} 条{table_name}数据 (插入/更新: {result} 行)")
                    return True
                else:
                    print(f"批量插入{table_name}失败")
                    return False
                    
            except Exception as upsert_error:
                print(f"UPSERT失败，尝试使用普通INSERT: {upsert_error}")
                
                # 回退到普通INSERT，忽略重复键错误
                fallback_query = query.replace(" ON DUPLICATE KEY UPDATE", "").replace("INSERT INTO", "INSERT IGNORE INTO")
                
                result = self.db.execute_batch(fallback_query, batch_data)
                if result is not None:
                    print(f"使用INSERT IGNORE成功处理 {len(batch_data)} 条{table_name}数据 (插入: {result} 行)")
                    return True
                else:
                    print(f"INSERT IGNORE失败")
                    return False
                    
        except Exception as e:
            print(f"批量插入{table_name}时出错: {e}")
            return False
                
    ##批量插入章节信息到数据库
    def batch_insert_chapters(self, chapters_data, comic_id):
        """批量插入章节数据到数据库"""
        if not self.db or not self.db.is_connected():
            print("数据库未连接，无法插入章节数据")
            return False
            
        try:
            for chapter in chapters_data:
                chapter_record = {
                    'chapter_id': chapter.get('chapterId'),
                    'comic_id': comic_id,
                    'comics_id': chapter.get('comicsId'),
                    'chapter_title': chapter.get('chapterTitle', ''),
                    'cover_img': chapter.get('coverImg', ''),
                    'chapter_num': chapter.get('chapterNum'),
                    'fake_watch_times': chapter.get('fakeWatchTimes'),
                    'created_at': chapter.get('createdAt', ''),
                    'watched': chapter.get('watched', ''),
                    'scan_time': time.strftime('%Y-%m-%d %H:%M:%S')
                }
                
                self.chapter_buffer.append(chapter_record)
                
                # 当缓冲区达到指定大小时，执行批量插入
                if len(self.chapter_buffer) >= self.chapter_batch_size:
                    insert_success = self._execute_batch_insert_chapters()
                    if not insert_success:
                        return False
                    
        except Exception as e:
            print(f"准备批量插入章节数据时出错: {e}")
            return False
            
        return True
        
    ##执行章节批量插入
    def _execute_batch_insert_chapters(self):
        """执行实际的章节批量插入操作，使用UPSERT提高性能"""
        if not self.chapter_buffer:
            return True
            
        try:
            # 构建UPSERT SQL语句
            columns = [
                'chapter_id', 'comic_id', 'comics_id', 'chapter_title', 'cover_img',
                'chapter_num', 'fake_watch_times', 'created_at', 'watched', 'scan_time'
            ]
            
            # 构建INSERT部分
            placeholders = ', '.join(['%s'] * len(columns))
            insert_part = f"INSERT INTO comics_chapters ({', '.join(columns)}) VALUES ({placeholders})"
            
            # 构建ON DUPLICATE KEY UPDATE部分
            update_columns = [col for col in columns if col not in ['id', 'chapter_id', 'comic_id', 'comics_id', 'created_at']]
            update_part = ', '.join([f"{col} = VALUES({col})" for col in update_columns])
            
            # 完整的UPSERT SQL
            query = f"{insert_part} ON DUPLICATE KEY UPDATE {update_part}"
            
            # 准备批量数据
            batch_data = []
            for record in self.chapter_buffer:
                values = [record[col] for col in columns]
                batch_data.append(values)
            
            # 使用新的重连机制执行批量插入
            success = self._execute_batch_insert_with_retry(query, batch_data, "章节")
            
            if success:
                # 清空缓冲区
                self.chapter_buffer.clear()
                return True
            else:
                return False
            
        except Exception as e:
            print(f"批量插入章节失败: {e}")
            print(f"SQL语句: {query}")
            return False

    ##强制插入剩余数据
    def flush_remaining_data(self):
        """强制插入缓冲区中剩余的数据"""
        comic_inserted = True
        if self.batch_buffer:
            print(f"插入剩余的 {len(self.batch_buffer)} 条漫画详情数据...")
            comic_inserted = self._execute_batch_insert_comic_detail()
            
        chapter_inserted = True
        if self.chapter_buffer:
            print(f"插入剩余的 {len(self.chapter_buffer)} 条章节数据...")
            chapter_inserted = self._execute_batch_insert_chapters()
            
        return comic_inserted, chapter_inserted
            
    ##数据库中获取未扫描完成的漫画列表
    def scan_comics_list(self, max_workers=3, batch_size=50):
        """
        扫描comics_list表中未扫描详情的漫画
        :param max_workers: 最大并发线程数
        :param batch_size: 每批处理的数据量
        """
        # 检查数据库连接
        if not self.db or not self.db.is_connected():
            print("数据库未连接，无法继续扫描")
            return
            
        ## 获取comics_list表数据字段scan_detail=0,未扫描的数据进行scan_comic_detail操作
        ## 操作完成需要设置scan_detail=1
        ## 加入多线程操作可以调整并发数
        
        try:
            # 获取未扫描详情的漫画总数
            count_query = "SELECT COUNT(*) as total FROM comics_list WHERE update_status=3 and (scan_detail = 0 OR scan_detail IS NULL) and JSON_CONTAINS(class_list, '{\"classId\": 7}')"
            count_result = self.execute_query_with_retry(count_query)
            total_count = count_result[0]['total'] if count_result else 0
            
            if total_count == 0:
                print("没有需要扫描详情的漫画数据")
                return
                
            print(f"发现 {total_count} 条未扫描详情的漫画数据")
            print(f"使用 {max_workers} 个线程并发处理，每批 {batch_size} 条数据")
            
            # 分批处理数据
            offset = 0
            processed_count = 0
            failed_count = 0
            
            while offset < total_count:
                # 检查数据库连接状态
                if not self.ensure_database_connection():
                    print("数据库连接失败，停止处理")
                    break
                    
                # 获取一批未扫描的数据
                batch_query = """
                    SELECT comic_id, comics_title 
                    FROM comics_list 
                    WHERE update_status=3 and (scan_detail = 0 OR scan_detail IS NULL) and JSON_CONTAINS(class_list, '{\"classId\": 7}')
                    ORDER BY id 
                    LIMIT %s OFFSET %s
                """
                batch_result = self.execute_query_with_retry(batch_query, (batch_size, offset))
                
                if not batch_result:
                    break
                    
                print(f"\n--- 处理第 {offset + 1} 到 {min(offset + batch_size, total_count)} 条数据 ---")
                
                # 改为单线程顺序处理，确保事务正常工作
                print("使用单线程顺序处理，确保事务正常工作...")
                
                for comic_data in batch_result:
                    comic_id = comic_data['comic_id']
                    comics_title = comic_data['comics_title']
                    
                    try:
                        print(f"正在扫描: {comics_title} (ID: {comic_id})")
                        
                        # 开始事务处理
                        try:
                            # 开始事务
                            print(f"开始事务: {comics_title}")
                            self.db.execute_query("START TRANSACTION")
                            
                            # 扫描漫画详情
                            success, error_msg = self.scan_comic_detail(comic_id)
                            
                            if success:
                                # 更新扫描状态为已完成
                                # 确保comic_id作为字符串正确处理
                                update_query = "UPDATE comics_list SET scan_detail = %s, scan_detail_time = NOW() WHERE comic_id = %s"
                                print(f"执行UPDATE: {update_query}")
                                print(f"参数: scan_detail=1, comic_id='{comic_id}' (类型: {type(comic_id)})")
                                
                                # 先检查当前值
                                check_query = "SELECT scan_detail FROM comics_list WHERE comic_id = %s"
                                check_result = self.db.execute_query(check_query, (comic_id,))
                                if check_result and len(check_result) > 0:
                                    old_value = check_result[0].get('scan_detail')
                                    print(f"更新前scan_detail值: {old_value}")
                                    
                                    if old_value == 1:
                                        print(f"✓ {comics_title} 已经是scan_detail=1，无需更新")
                                        self.db.execute_query("COMMIT")
                                        processed_count += 1
                                    else:
                                        # 执行UPDATE
                                        update_result = self.execute_update_with_retry(update_query, (1, comic_id))
                                        
                                        if update_result:
                                            # 提交事务
                                            self.db.execute_query("COMMIT")
                                            print(f"✓ {comics_title} 扫描完成，状态已更新为 scan_detail=1")
                                            processed_count += 1
                                        else:
                                            # 回滚事务
                                            self.db.execute_query("ROLLBACK")
                                            print(f"⚠ {comics_title} 扫描完成，但状态更新失败，已回滚")
                                            failed_count += 1
                                else:
                                    print(f"⚠ 无法检查当前scan_detail值")
                                    failed_count += 1
                            else:
                                # 扫描失败，更新状态
                                # 确保comic_id作为字符串正确处理
                                update_query = "UPDATE comics_list SET scan_detail = -1, scan_detail_time = NOW(), scan_detail_error = %s WHERE comic_id = %s"
                                print(f"执行失败UPDATE: {update_query}")
                                print(f"参数: error_msg='{error_msg[:500]}', comic_id='{comic_id}' (类型: {type(comic_id)})")
                                
                                # 先检查当前值
                                check_query = "SELECT scan_detail FROM comics_list WHERE comic_id = %s"
                                check_result = self.db.execute_query(check_query, (comic_id,))
                                if check_result and len(check_result) > 0:
                                    old_value = check_result[0].get('scan_detail')
                                    print(f"更新前scan_detail值: {old_value}")
                                    
                                    if old_value == -1:
                                        print(f"✓ {comics_title} 已经是scan_detail=-1，无需更新")
                                        self.db.execute_query("COMMIT")
                                        failed_count += 1
                                    else:
                                        # 执行UPDATE
                                        update_result = self.execute_update_with_retry(update_query, (error_msg[:500], comic_id))
                                        
                                        if update_result:
                                            # 提交事务
                                            self.db.execute_query("COMMIT")
                                            print(f"✗ {comics_title} 扫描失败，状态已更新为 scan_detail=-1")
                                            failed_count += 1
                                        else:
                                            # 回滚事务
                                            self.db.execute_query("ROLLBACK")
                                            print(f"⚠ {comics_title} 扫描失败，状态更新也失败，已回滚")
                                            failed_count += 1
                                else:
                                    print(f"⚠ 无法检查当前scan_detail值")
                                    failed_count += 1
                                    
                        except Exception as transaction_error:
                            # 回滚事务
                            try:
                                self.db.execute_query("ROLLBACK")
                                print(f"⚠ {comics_title} 事务处理异常，已回滚: {transaction_error}")
                            except:
                                pass
                            failed_count += 1
                        
                    except Exception as e:
                        error_msg = f"扫描异常: {comic_id} - {str(e)}"
                        print(f"✗ {error_msg}")
                        failed_count += 1
                        
                        # 尝试回滚任何未完成的事务
                        try:
                            self.db.execute_query("ROLLBACK")
                        except:
                            pass
                
                # 更新偏移量
                offset += batch_size
                
                # 添加延迟，避免请求过于频繁
                if offset < total_count:
                    print("等待3秒后继续下一批...")
                    time.sleep(3)
            
            # 输出最终统计
            print(f"\n=== 扫描完成 ===")
            print(f"总数据量: {total_count}")
            print(f"成功处理: {processed_count}")
            print(f"处理失败: {failed_count}")
            print(f"成功率: {(processed_count / total_count * 100):.2f}%")
            
            # 如果有失败的记录，显示详细信息
            if failed_count > 0:
                print(f"\n=== 失败记录详情 ===")
                failed_records = self.get_failed_scans(limit=10)
                for i, failed in enumerate(failed_records, 1):
                    print(f"{i}. {failed['comics_title']} (ID: {failed['comic_id']})")
                    print(f"   错误: {failed['scan_detail_error']}")
                    print(f"   时间: {failed['scan_detail_time']}")
                    print()
                    
                print(f"提示: 可以使用 retry_failed_scans() 方法重试失败的扫描")
            
        except Exception as e:
            print(f"批量扫描漫画详情失败: {e}")
            import traceback
            traceback.print_exc()
            
    ##获取未扫描详情的漫画数量
    def get_unscanned_count(self):
        """获取未扫描详情的漫画数量"""
        if not self.db or not self.db.is_connected():
            return 0
            
        try:
            query = "SELECT COUNT(*) as total FROM comics_list WHERE update_status=3 and (scan_detail = 0 OR scan_detail IS NULL) and JSON_CONTAINS(class_list, '{\"classId\": 7}')"
            result = self.execute_query_with_retry(query)
            return result[0]['total'] if result else 0
        except Exception as e:
            print(f"获取未扫描数量失败: {e}")
            return 0
            
    ##获取扫描失败的漫画列表
    def get_failed_scans(self, limit=100):
        """获取扫描失败的漫画列表"""
        if not self.db or not self.db.is_connected():
            return []
            
        try:
            query = """
                SELECT comic_id, comics_title, scan_detail_error, scan_detail_time
                FROM comics_list 
                WHERE scan_detail = -1
                ORDER BY scan_detail_time DESC
                LIMIT %s
            """
            result = self.execute_query_with_retry(query, (limit,))
            return result if result else []
        except Exception as e:
            print(f"获取失败扫描列表失败: {e}")
            return []
            
    ##重试扫描失败的漫画
    def retry_failed_scans(self, max_workers=2):
        """重试扫描失败的漫画"""
        failed_scans = self.get_failed_scans()
        
        if not failed_scans:
            print("没有扫描失败的漫画")
            return
            
        print(f"发现 {len(failed_scans)} 条扫描失败的漫画，开始重试...")
        
        # 重置失败状态
        for failed_scan in failed_scans:
            comic_id = failed_scan['comic_id']
            reset_query = f"UPDATE comics_list SET scan_detail = 0, scan_detail_error = NULL WHERE comic_id = '{comic_id}'"
            self.execute_update_with_retry(reset_query, (comic_id,))
            
        # 重新扫描
        self.scan_comics_list(max_workers=max_workers, batch_size=20)
            
    ##漫画详情扫描并保存到数据库
    def scan_comic_detail(self, comic_id):
        """
        扫描漫画详情并保存到数据库
        返回: (success, error_message)
        注意: 此方法应在事务中调用，不会自动提交
        """
        # 检查数据库连接状态
        if not self.db or not self.db.is_connected():
            error_msg = "数据库连接已断开，无法继续扫描"
            print(f"✗ {error_msg}")
            return False, error_msg
            
        try:
            current_timestamp = int(time.time() * 1000)
            url = f"{self.web_url}/api/comics/base/info?id={comic_id}&_t={current_timestamp}"
            response = self.comm.get_resp(url)
            
            if not response or response.status_code != 200:
                error_msg = f"HTTP请求失败: {response.status_code if response else 'No response'}"
                print(f"✗ {error_msg}")
                return False, error_msg
                
            response_data = response.json()
            comic_data = vp(response_data['encData'])
            print(f"{comic_data['comicsTitle']}开始扫描")
            
            # 获取domain信息
            domain = comic_data.get('domain', '')
            
            # 保存漫画基本信息
            print("正在保存漫画基本信息...")
            comic_success = self.batch_insert_comic_detail(comic_data, domain)
            if not comic_success:
                error_msg = "保存漫画基本信息失败"
                print(f"✗ {error_msg}")
                return False, error_msg
            
            # 保存章节信息
            ep_data = comic_data.get('chapterList', [])
            if ep_data:
                print(f"正在保存 {len(ep_data)} 条章节信息...")
                chapter_success = self.batch_insert_chapters(ep_data, comic_id)
                if not chapter_success:
                    error_msg = "保存章节信息失败"
                    print(f"✗ {error_msg}")
                    return False, error_msg
                
            # 强制插入剩余数据并验证结果
            print("正在验证数据库插入结果...")
            comic_inserted, chapter_inserted = self.flush_remaining_data()
            
            if not comic_inserted:
                error_msg = "漫画详情数据插入失败"
                print(f"✗ {error_msg}")
                return False, error_msg
                
            if ep_data and not chapter_inserted:
                error_msg = "章节数据插入失败"
                print(f"✗ {error_msg}")
                return False, error_msg
                
            print(f"✓ {comic_data['comicsTitle']}扫描完成！")
            print(f"✓ 所有数据库操作成功，准备返回 True")
            return True, None
            
        except json.JSONDecodeError as json_error:
            error_msg = f"JSON解析失败: {json_error}"
            print(f"✗ {error_msg}")
            return False, error_msg
        except Exception as e:
            error_msg = f"扫描漫画详情失败: {e}"
            print(f"✗ {error_msg}")
            return False, error_msg

    ##验证扫描状态
    def verify_scan_status(self, comic_id):
        """验证指定漫画的扫描状态"""
        if not self.db or not self.db.is_connected():
            print("数据库未连接，无法验证状态")
            return None
            
        try:
            query = """
                SELECT comic_id, comics_title, scan_detail, scan_detail_time, scan_detail_error
                FROM comics_list 
                WHERE comic_id = %s
            """
            result = self.execute_query_with_retry(query, (comic_id,))
            
            if result:
                record = result[0]
                status_map = {0: "未扫描", 1: "扫描完成", -1: "扫描失败", None: "状态未知"}
                status = status_map.get(record['scan_detail'], f"未知状态({record['scan_detail']})")
                
                print(f"漫画: {record['comics_title']}")
                print(f"ID: {record['comic_id']}")
                print(f"扫描状态: {status}")
                print(f"扫描时间: {record['scan_detail_time']}")
                if record['scan_detail_error']:
                    print(f"错误信息: {record['scan_detail_error']}")
                    
                return record
            else:
                print(f"未找到ID为 {comic_id} 的漫画记录")
                return None
                
        except Exception as e:
            print(f"验证扫描状态失败: {e}")
            return None
            
    ##关闭数据库连接
    def close_database(self):
        """关闭数据库连接"""
        try:
            # 确保插入剩余数据
            self.flush_remaining_data()
            
            # 关闭数据库连接
            if self.db:
                try:
                    self.db.disconnect()
                    print("数据库连接已关闭")
                except Exception as e:
                    print(f"关闭数据库连接时出错: {e}")
                    
        except Exception as e:
            print(f"关闭数据库连接时出错: {e}")


if __name__ == "__main__":
    scan_comic = ScanComic()
    try:
        # 检查数据库连接
        if not scan_comic.db or not scan_comic.db.is_connected():
            print("数据库连接失败，程序退出")
            exit(1)
            
        print("=== 漫画详情扫描程序 ===")
        print("1. 查看扫描状态")
        print("2. 开始批量扫描")
        print("3. 重试失败的扫描")
        print("4. 扫描单个漫画")
        print("5. 验证漫画扫描状态")
        
        choice = "2"
        
        if choice == "1":
            # 查看扫描状态
            unscanned_count = scan_comic.get_unscanned_count()
            print(f"\n未扫描详情的漫画数量: {unscanned_count}")
            
            if unscanned_count == 0:
                # 检查是否有扫描失败的漫画
                failed_scans = scan_comic.get_failed_scans()
                if failed_scans:
                    print(f"\n发现 {len(failed_scans)} 条扫描失败的漫画:")
                    for failed in failed_scans[:5]:  # 只显示前5条
                        print(f"  - {failed['comics_title']} (错误: {failed['scan_detail_error']})")
                else:
                    print("\n所有漫画详情都已扫描完成！")
                    
        elif choice == "2":
            scan_comic.scan_comics_list(max_workers=20, batch_size=200)
            
        elif choice == "3":
            # 重试失败的扫描
            failed_scans = scan_comic.get_failed_scans()
            if failed_scans:
                print(f"发现 {len(failed_scans)} 条扫描失败的漫画，开始重试...")
                max_workers = int(input("请输入重试并发线程数 (建议2-5): ") or "2")
                scan_comic.retry_failed_scans(max_workers=max_workers)
            else:
                print("没有扫描失败的漫画")
                
        elif choice == "4":
            # 扫描单个漫画
            comic_id = input("请输入漫画ID: ").strip()
            if comic_id:
                success, error = scan_comic.scan_comic_detail(comic_id)
                if success:
                    print("✓ 扫描成功")
                else:
                    print(f"✗ 扫描失败: {error}")
            else:
                print("漫画ID不能为空")
                
        elif choice == "5":
            # 验证漫画扫描状态
            comic_id = input("请输入要验证的漫画ID: ").strip()
            if comic_id:
                scan_comic.verify_scan_status(comic_id)
            else:
                print("漫画ID不能为空")
                
        else:
            print("无效选择")
                
    except KeyboardInterrupt:
        print("\n用户中断操作")
    except Exception as e:
        print(f"程序执行异常: {e}")
        import traceback
        traceback.print_exc()
    finally:
        # 确保程序结束时关闭数据库连接
        scan_comic.close_database()


